package net.bplaced.streetfighter.fragment;

import net.bplaced.streetfighter.R;
import net.bplaced.streetfighter.ReplyToCommentActivity;
import net.bplaced.streetfighter.adapter.CommentListAdapter;
import net.bplaced.streetfighter.lib.async.task.CommentLoaderTask;
import net.bplaced.streetfighter.lib.model.Comment;
import net.bplaced.streetfighter.lib.utils.CallBack;
import net.bplaced.streetfighter.lib.utils.RuntimeData;
import net.bplaced.streetfighter.lib.utils.RuntimeDataKey;
import net.bplaced.streetfighter.lib.utils.RuntimeDataObject;
import net.bplaced.streetfighter.lib.utils.ServiceReturnPackage;
import net.bplaced.streetfighter.lib.utils.StreetfighterUtils;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * @author Sebastian Hoffmann <bo.hoffi@googlemail.com>
 */
public class GuestbookFragment
        extends Fragment {

    private RelativeLayout view = null;

    private ListView commentList;

    private Comment contextMenuComment;
    private Integer startIndex;

    private boolean isTablet;

    private CommentListAdapter commentAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        this.view = (RelativeLayout) inflater.inflate(R.layout.view_guestbook, container, false);

        this.prepareView();

        if (RuntimeData.getInstance().get(RuntimeDataKey.IS_TABLET) != null) {
            this.isTablet = (Boolean) RuntimeData.getInstance().get(RuntimeDataKey.IS_TABLET).getData();
        }

        this.fetchComments();

        return this.view;
    }

    private void prepareView() {

        this.commentList = (ListView) this.view.findViewById(R.id.guestbook_comment_list);

        final Button loadMoreCommentsBtn = (Button) this.view.findViewById(R.id.guestbook_load);
        loadMoreCommentsBtn.setOnClickListener(this.loadMoreCommentsClickListener);

        final Button newEntryBtn = (Button) this.view.findViewById(R.id.guestbook_post);
        newEntryBtn.setOnClickListener(this.newEntryClickListener);
    }

    private void fetchComments() {

        this.commentAdapter = new CommentListAdapter(this.getActivity(), this);
        this.startIndex = 0;

        final CommentLoaderTask task =
                new CommentLoaderTask(this.getActivity(), this.getResources().getString(
                        R.string.guestbook_progress_message), this.onFinishedLoading);
        task.execute(this.startIndex);
    }

    /**
     * Deklariert einen Callback, welcher zum Ende des Serviceaurufes aufgerufen wird.
     */
    private final CallBack<ServiceReturnPackage<Comment[]>> onFinishedLoading =
            new CallBack<ServiceReturnPackage<Comment[]>>() {

                @Override
                public void callbackAction(ServiceReturnPackage<Comment[]> result) {

                    if (result != null) {
                        if ((result.getContent() != null) && (result.getContent().length > 0)) {

                            GuestbookFragment.this.commentAdapter.addAll(result.getContent());
                            GuestbookFragment.this.commentList.setAdapter(GuestbookFragment.this.commentAdapter);

                        } else {

                            GuestbookFragment.this.startIndex -= 10;
                            Toast.makeText(GuestbookFragment.this.getActivity(), result.getErrorMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                };
            };

    private final View.OnClickListener loadMoreCommentsClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            GuestbookFragment.this.startIndex += 10;

            final CommentLoaderTask task =
                    new CommentLoaderTask(GuestbookFragment.this.getActivity(), GuestbookFragment.this.getResources()
                            .getString(R.string.guestbook_progress_message), GuestbookFragment.this.onFinishedLoading);
            task.execute(GuestbookFragment.this.startIndex);
        }
    };

    private final View.OnClickListener newEntryClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            GuestbookFragment.this.navigateToPostActivity(GuestbookFragment.this.createEmptyComment());
        }
    };

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

        // Hack for the menu item to appear only once
        if (menu.size() == 0) {
            menu.add(0, 0, 0, this.getResources().getString(R.string.guestbook_context_menu_reply));
        }

        // Hack to get the comment of the context menu
        this.contextMenuComment = (Comment) v.getTag();
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        Comment comment = this.contextMenuComment;

        if (comment == null) {
            comment = this.createEmptyComment();
        }

        this.navigateToPostActivity(comment);

        return false;
    }

    private void navigateToPostActivity(Comment comment) {

        RuntimeData.getInstance().put(RuntimeDataKey.COMMENT, new RuntimeDataObject<Comment>(comment));

        StreetfighterUtils.changeContent(this.getFragmentManager(), this.getActivity(), this.isTablet,
                R.id.main_detail_container, new ReplyFragment(), new Intent(this.getActivity(),
                        ReplyToCommentActivity.class));
    }

    private Comment createEmptyComment() {

        final Comment comment = new Comment();
        comment.id = 0;
        comment.author = "";
        comment.authorEmail = "";
        comment.authorUrl = "";
        comment.commentDateTimeString = "";
        comment.commentText = "";
        comment.childComments = new Comment[0];

        return comment;
    }
}